package com.example.myblog.controller;

import com.example.myblog.pojo.User;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;


/**
 * @BelongsProject: MyBlog
 * @BelongsPackage: com.example.myblog.controller
 * @ClassName RegisterController
 * @CreateTime: 2025-06-09  14:56
 * @Author: TangLiFei
 */
@Controller
public class RegisterController {

    @Autowired
    private UserService userService;

    @RequestMapping("/registerPage")
    public String registerPage() {
        return "register";
    }

    @RequestMapping("/register")
    public String register(User user, HttpServletRequest request) {
        System.out.println("注册请求接收：" + user.getAccount() + "/" + user.getPwd());
        try {
            userService.register(user);
            System.out.println("注册成功，重定向到登录页");
            return "redirect:/";
        } catch (RuntimeException e) {
            // 这里可以更细致区分异常类型，比如判断异常消息
            if (e.getMessage().contains("该账号已存在")) {
                request.setAttribute("error", "注册失败，该账号已存在");
            } else {
                request.setAttribute("error", "注册失败，请稍后重试");
            }
            System.out.println("注册失败：" + e.getMessage());
            return "redirect:/registerPage?error=true";
        }
    }
}